package core

import (
	"container/list"
	"errors"
	"gitee.com/cooge/impush/message"
)

type MessageHandlerFunc func(string, *message.Message, error)

var mfilterlist = list.New()

func AddMessageFilter(fhf MessageHandlerFunc) {
	mfilterlist.PushBack(fhf)
}

func messageHeadle(userId string, msg *message.Message, err error) {
	for e := mfilterlist.Front(); e != nil; e = e.Next() {
		fh, ok := e.Value.(MessageHandlerFunc)
		if ok {
			fh(userId, msg, err)
		}
	}
}

func SendMessage(userId string, mgs *message.Message) (int, error) {
	us := GetUser(userId)
	if us != nil {
		num, err := us.SendMessage(mgs)
		messageHeadle(userId, mgs, err)
		return num, err
	}
	return 0, errors.New(message.NO_USER)
}
